package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.system.domain.RoleCamera;
import com.ruoyi.system.domain.vo.AreaCameraVo;
import com.ruoyi.system.domain.vo.RoleCameraVo;
import com.ruoyi.system.mapper.RoleCameraMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IRoleCameraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-07-21 15:41
 **/
@Service
@Slf4j
public class RoleCameraServiceImpl extends ServiceImpl<RoleCameraMapper, RoleCamera> implements IRoleCameraService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 根据角色id查询角色的摄像头列表
     * @param roleId 角色id
     * @return
     */
    @Override
    public RoleCameraVo getRoleCameraListByRoleId(Long roleId) {
        RoleCameraVo roleCameraVo = new RoleCameraVo();
        List<AreaCameraVo> allArea = this.baseMapper.selectAllArea();
        List<AreaCameraVo> allRoleAreaCameraList = this.getAllAreaCameraList(allArea);
        roleCameraVo.setAreaCameraList(allRoleAreaCameraList);
        roleCameraVo.setCameraIdList(this.baseMapper.selectCameraIdListByRoleId(roleId));
        return roleCameraVo;
    }

    /**
     * 查询当前用户可访问的区域和摄像头
     * @param username
     * @return
     */
    public List<AreaCameraVo> getUserAccessAreaCamera(String username) {
        SysUser sysUser = sysUserMapper.selectUserByUserName(username);
        if(sysUser == null) {
            throw new ServiceException("用户不存在");
        }
        List<SysRole> roles = sysUser.getRoles();
        if(CollectionUtils.isEmpty(roles)) {
            return new ArrayList<>();
        }
        List<Long> roleIdList = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<Long> cameraIdList = this.baseMapper.selectCameraIdListByRoleIdList(roleIdList);
        if(CollectionUtils.isEmpty(cameraIdList)) {
            return new ArrayList<>();
        }
        List<AreaCameraVo> areaCameraList = this.baseMapper.selectAreaCameraByIdList(cameraIdList);
        return this.getAllAreaCameraList(areaCameraList);
    }

    /**
     * 查询所有的区域和摄像头
     * @param
     * @return
     */
    public List<AreaCameraVo> getAllAreaCameraList(List<AreaCameraVo> allArea) {
        //所有区域和摄像头
        if(allArea.isEmpty()) {
            return new ArrayList<>();
        }
        // 2. 构建区域的树形结构
        List<AreaCameraVo> result = new ArrayList<>();
        for (AreaCameraVo area : allArea) {
            // 如果是一级区域，找到该区域的所有子节点，并添加到结果
            if(area.getParentId() == 0L) {
                this.buildAreaTree(allArea,area);
                result.add(area);
            }
        }
        return result;
    }

    /**
     * 给角色设置两个默认的区域
     * @param roleId
     */
    public void insertDefaultCameraArea(Long roleId) {
        try {
            Long qyhjId = this.baseMapper.queryAreaIdByName("企业环境", 0L);
            if(qyhjId != null) {
                Long area2Id = this.baseMapper.queryAreaIdByName("空中看山东新美达公司", qyhjId);
                Long area3Id = this.baseMapper.queryAreaIdByName("生产区航拍", qyhjId);
                if(area2Id != null) {
                    List<RoleCamera> list = new ArrayList<>();
                    RoleCamera roleCamera1 = new RoleCamera();
                    roleCamera1.setRoleId(roleId);
                    roleCamera1.setCameraId(qyhjId);
                    list.add(roleCamera1);
                    RoleCamera roleCamera2 = new RoleCamera();
                    roleCamera2.setRoleId(roleId);
                    roleCamera2.setCameraId(area2Id);
                    list.add(roleCamera2);
                    if(area3Id != null) {
                        RoleCamera roleCamera3 = new RoleCamera();
                        roleCamera3.setRoleId(roleId);
                        roleCamera3.setCameraId(area3Id);
                        list.add(roleCamera3);
                    }
                    this.saveBatch( list);
                }
            }
        }catch (Exception e) {
            log.error("给角色增加默认摄像头区域异常：{}", ExceptionUtil.getExceptionMessage(e));
        }
    }

    private void buildAreaTree(List<AreaCameraVo> allArea,AreaCameraVo  area) {
        // 查找该节点的所有子节点
        List<AreaCameraVo> children = this.getChildren(allArea,area);
        area.setChildren(children);
        for (AreaCameraVo child : children) {
            List<AreaCameraVo> children1 = this.getChildren(allArea, child);
            child.setChildren(children1);
            if(!children1.isEmpty()) {
                this.buildAreaTree(allArea,child);
            }
        }
    }

    private List<AreaCameraVo> getChildren(List<AreaCameraVo> allArea, AreaCameraVo area) {
        List<AreaCameraVo> children = new ArrayList<>();
        for (AreaCameraVo child : allArea) {
            if(child.getParentId().equals(area.getId())) {
                children.add(child);
            }
        }
        return children;
    }

}
